<template>
  <div>
    <el-form ref="adminUser" v-loading="loading" :rules="rules" style="margin-top: 30px;" :model="adminUser" label-width="100px">
      <el-form-item label="密码" prop="password">
        <el-input v-model="adminUser.password" type="password" />
      </el-form-item>
      <el-form-item label="提交" label-width="100px">
        <el-button type="primary" @click="submitForm('adminUser')">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import adminApi from '@/api/admin'
import md5 from 'js-md5'
export default {
  name: 'AdminUpdatePassword',
  props: {
    adminUser: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      rules: { // 密码校验规则
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在6-12之间', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.adminUser.password !== null) {
            this.adminUser.password = md5(this.adminUser.password)
          }
          this.loading = true
          adminApi.updatePwd(this.adminUser).then(res => {
            if (res.code === 200) {
              this.adminUser.password = null
              this.loading = false
              this.$message.success('更新成功')
              this.$emit('closeUpdateDialog')
            } else {
              this.loading = false
            }
          }).catch(err => {
            console.log(err)
            this.loading = false
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
